package com.lazar.dao;

import com.lazar.model.Student;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class StudentDao {
    public List<Student> getAllStudent(){
        List<Student> list = new ArrayList<>();
        Connection conn = DbHelper.getConn();

        String sql = "select * from t_student";

        try {
            PreparedStatement pt = conn.prepareStatement(sql);

            ResultSet rs = pt.executeQuery();

            while (rs.next()){
                Student stu =  new Student();
                stu.setSid(rs.getInt("sid"));
                stu.setName(rs.getString("name"));
                stu.setSex(rs.getString("sex"));
                stu.setBirth(rs.getDate("birth"));

                list.add(stu);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return list;
    }

    public boolean addStudent(Student stu){
        String sql = "insert into t_student(sid,name,sex,birth) values(default,?,?,?)";
        Connection db = DbHelper.getConn();
        try {
            PreparedStatement pt = db.prepareStatement(sql);
            pt.setString(1,stu.getName());
            pt.setString(2,stu.getSex());

            Date tdate = new Date(stu.getBirth().getTime());
            pt.setDate(3, tdate);

            int count = pt.executeUpdate();
            pt.close();
            return count>0?true:false;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
